package myPackage;

import java.net.*;
import java.util.*;
import java.sql.*;

import net.jxta.access.AccessService;
import net.jxta.access.AccessService.AccessResult;
import net.jxta.credential.Credential;
import net.jxta.credential.PrivilegedOperation;
import net.jxta.document.TextElement;
import net.jxta.exception.PeerGroupException;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.protocol.ModuleImplAdvertisement;
import net.jxta.protocol.PeerGroupAdvertisement;


public class RBACUtil {

	private static Connection conn;
    static ChatInput chatIn = null; 
    static ChatOutput chatOut=null; 
    public PeerGroup peergroup ;
    public String[] nameList;
    private PrivilegedOperation myOp;
    public AccessResult UNDETERMINED,DISALLOWED,PERMITTED,PERMITTED_EXPIRED;
    
    
    public boolean checkPermission(String peerid,String permission){
    	String peername = null ;
    	// using fix length string array
    	String[] rolename = new String[10];
    	boolean result = false;
    	conn = null;
    	if(connection()){
    		try{
    			Statement stmt = conn.createStatement();
    			//get the user name from peerid
    			ResultSet res0 = stmt.executeQuery("SELECT * FROM users WHERE peerid = '" + peerid+"'");
    			while(res0.next()){
    				peername = res0.getString("username");
    			}
    			
    			//get the peer role from peer name
    			if( peername != null ){
    				int i = 0;
    				ResultSet res1 = stmt.executeQuery("SELECT * FROM user_role_assignments WHERE username = '" + peername+ "'");
    				while(res1.next()){
    					rolename[i++] = res1.getString("role_name");
    				}
    			}
    			
    			//search for the role and permission in table
    			int i = 0;
    			while ( i < rolename.length ){  
    				
    				String currentrole = rolename[i++];
    				ResultSet res2 = stmt.executeQuery("SELECT * FROM role_permission_assignments WHERE role_name = '" + currentrole + "'");
    				while(res2.next()){
    					if (res2.getString("permission_name").equalsIgnoreCase(permission)){
    						result = true;
    						return result;
    					}
    				}
    				
    			}
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    		
    	}
    	
    	return result;
    }
    
	public boolean UpdateLocation(String peername, String location, String time){
		boolean update = true;		
		System.out.println("location received! "+ peername +" at "+ location);
		
		conn = null;
		if (connection()){
		try{
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("UPDATE users SET location = '"+location+"' WHERE username = '"+peername+"'");
			System.out.println("UPDATE user "+ peername +" location as "+ location);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		}
		
		return update;
	}
	
	public String getRoleName(String peername){
		String rolename = null;
		conn = null;
		if(connection()){
			try{
				Statement stmt = conn.createStatement();
				ResultSet res = stmt.executeQuery("SELECT * FROM user_role_assignments WHERE username = '" + peername +"' AND enabled = '1'");
				while(res.next()){
					rolename = res.getString("role_name");
				}
			
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
		return rolename;
	}
	
	public String getLocation(String peername){
		
		String location = null;		
		conn = null;
		if (connection()){
			try{
				Statement stmt = conn.createStatement();
				ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE username ='"+peername+"'");
				while(res.next()){
				location = res.getString("location");				
				System.out.println("Get user "+ peername +" location as "+ location);
			}}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}		
		return location;
	}
	
	public static String[] AllRoles()
	{
		
		ArrayList<String> list = new ArrayList<String>();
		conn = null;
		if (connection()){
		
		try
		{
			Statement stmt = conn.createStatement();
			ResultSet res = stmt.executeQuery("SELECT * FROM roles");
			while(res.next())
			{
				String role_name = res.getString("name");
				list.add(role_name);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}}
		
		String[] result = new String[list.size()];
		
		for(int i = 0 ; i<list.size(); i++){
			result[i] = list.get(i);
		}
		
		return result;
	}	
	
private static boolean connection() {
		
		String url = "jdbc:mysql://localhost:3306/";
		String dbname = "gtrbac";
		String driver = "com.mysql.jdbc.Driver";
		String username = "root";
		String password = "root";
		
		try
		{
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url+dbname, username, password);		
			System.out.println("Connected to Database");
			return true;
		}
		catch (Exception e)
		{
			
			e.printStackTrace();
		}
		return false;
	}

	public boolean LotAccessServiceinit(PeerGroup group, Credential offerer) throws PeerGroupException{
		this.peergroup = group;
		ID assignedID = group.getPeerGroupID();
		
		AccessService lotAccessService = this.peergroup.getAccessService();
		if(lotAccessService != null){
		System.out.println("AccessService granted!");}
		ModuleImplAdvertisement module = (ModuleImplAdvertisement) peergroup.getImplAdvertisement();
		lotAccessService.init(peergroup, assignedID, module);
		Object subject = (Object) "JOINGROUP";
		
		myOp = lotAccessService.newPrivilegedOperation(subject, offerer);
		System.out.println("The Credential is :\n"+offerer.toString());
		
		
		if(lotAccessService.doAccessCheck(myOp, offerer)== AccessResult.PERMITTED){
		System.out.println("Service Access Check permitted!");
		}
		else{System.out.println("Service Access Check Denied!");}
		PeerGroupAdvertisement configAdv = group.getPeerGroupAdvertisement();
		TextElement myParam = (TextElement) configAdv.getServiceParam(group.membershipClassID);
		if (null == myParam) {
            throw new PeerGroupException("parameters for group service are missing.");
        }
		
		Enumeration allACLS = myParam.getChildren();
		while (allACLS.hasMoreElements()) {
            TextElement anACL = (TextElement) allACLS.nextElement();
            
            if (!anACL.getName().equals("ACL")) {
                continue;
            }
            
            String text = anACL.getTextValue();
            String operation = text.substring(0, text.indexOf(":"));
            String namelists = text.substring(text.indexOf(":")+1);
            
            StringTokenizer st = new StringTokenizer(namelists, ",");
            nameList = new String[st.countTokens()];
            int count = 0;
            while(st.hasMoreTokens()){
            	nameList[count++] = st.nextToken();
            	}
            System.out.println("NameLists : "+ nameList[1].toString());
	}
		return true;
	}
}
